import 'package:flutter_common/ui/widget/popup_menu_button.dart';
import 'package:flutter/material.dart';

///popup弹窗，优先取弹窗内容builder，为空则取itemBuilder
Future<T?> showPopupMenu<T>(
    BuildContext context, {
      FxPopupMenuItemBuilder<T>? builder,
      PopupMenuItemBuilder<T>? itemBuilder,
      Offset offset = Offset.zero,
      PopupMenuPosition? position,
      PopupMenuItemSelected<T>? onSelected,
      PopupMenuCanceled? onCanceled,
      VoidCallback? onOpened,
      T? initialValue,
      EdgeInsetsGeometry padding = const EdgeInsets.all(8.0),
    }) async {
  final List<PopupMenuEntry<T>> items = builder != null
      ? builder.call(context).map((e) => FxPopupMenuItem<T>(e)).toList()
      : itemBuilder?.call(context) ?? [];
  if(items.isEmpty){
    return null;
  }
  final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context);
  final RenderBox button = context.findRenderObject()! as RenderBox;
  final RenderBox overlay =
  Navigator.of(context).overlay!.context.findRenderObject()! as RenderBox;
  final PopupMenuPosition popupMenuPosition =
      position ?? popupMenuTheme.position ?? PopupMenuPosition.over;
  final Offset offset0;
  switch (popupMenuPosition) {
    case PopupMenuPosition.over:
      offset0 = offset;
      break;
    case PopupMenuPosition.under:
      offset0 = Offset(0.0, button.size.height - (padding.vertical / 2)) + offset;
      break;
  }
  final RelativeRect pos = RelativeRect.fromRect(
    Rect.fromPoints(
      button.localToGlobal(offset0, ancestor: overlay),
      button.localToGlobal(button.size.bottomRight(Offset.zero) + offset0,
          ancestor: overlay),
    ),
    Offset.zero & overlay.size,
  );
  // Only show the menu if there is something to show
  onOpened?.call();
  return showMenu<T?>(
    context: context,
    elevation: popupMenuTheme.elevation,
    shadowColor: popupMenuTheme.shadowColor,
    surfaceTintColor: popupMenuTheme.surfaceTintColor,
    items: items,
    initialValue: initialValue,
    position: pos,
    shape: popupMenuTheme.shape,
    color: popupMenuTheme.color,
  ).then<T?>((T? newValue) {
    if (!context.mounted) {
      return newValue;
    }
    if (newValue == null) {
      onCanceled?.call();
      return newValue;
    }
    onSelected?.call(newValue);
    return newValue;
  });
}


